<template>
	<!--聊天界面-->
	<view class="page-content">
		<view class="page-top" v-if="chat_type==='GROUP'">
			<block v-for="(item,index) in obj.list" :key="index">
				<view class="top-imgs" @click.stop="todet(item.uid,item.type)">
					<image class="top-img" :src="item.img || $mAssetsPath.icon_mrtx"></image>
				</view>
			</block>
			<view class="top-imgs">
				<image class="top-img" :src="$mAssetsPath.icon_add2" @click="toadd"></image>
			</view>
			<view class="top-imgs" v-if="role">
				<image class="top-img" :src="$mAssetsPath.icon_less" @click="toless"></image>
			</view>
		</view>
		<view class="page-body">
			<view class="body-box" v-if="chat_type==='GROUP'" @click="jiesan('edit')">
				<view class="body-box-l">群昵称</view>
				<view class="body-box-r">{{title}}
					<view class="icon-gd icons icon-gengduo" v-if="role"></view>
				</view>
			</view>

			<view class="body-box2">
				<view class="box-cen" v-if="chat_type === 'GROUP'">
					<view class="box-cen-l">消息免打扰</view>
					<switch @change="switchChange1" :checked="checked1" color="#198FFF" style="transform:scale(0.7)" />
				</view>
				<view class="box-cen">
					<view class="box-cen-l">置顶聊天</view>
					<switch @change="switchChange2" :checked="checked2" color="#198FFF" style="transform:scale(0.7)" />
				</view>
			</view>

			<view class="body-box" @click="jiesan('qingchu')">
				<view class="body-box-l">清空聊天记录</view>
				<view class="body-box-r">
					<view class="icon-gd icons icon-gengduo"></view>
				</view>
			</view>
			<view class="body-box3" v-if="chat_type==='GROUP'">
				<view class="body-box-c" @click="jiesan('jiesan')">{{ role?'解散群组':'退出群组'}}</view>
			</view>
		</view>
		<w-popup :show="showtip" :type="type1" @change="change1">
			<view class="w-tip">
				<view class="w-tit" v-if="tip_type==='qingchu'">删除聊天记录</view>
				<view class="w-tit" v-else-if="tip_type==='jiesan'">{{role?'解散群聊':'退出群聊'}}</view>
				<view class="w-tit" v-else>编辑</view>
				<view class="w-con" v-if="tip_type==='qingchu'">是否删除？</view>
				<view class="w-con" v-else-if="tip_type==='jiesan'">{{role?'是否解散？':'是否退群？'}}</view>
				<view class="w-con" v-else-if="tip_type==='edit'">
					<view class="input-row">
						<input class="input-row-w" type="text" v-model="searchVal" placeholder="请输入群新名称"
							confirm-type="search" placeholder-style="color:#999"></input>
						<image class="icon-tb3" v-if="searchVal!=''" @click.stop="clear"
							:src="$mAssetsPath.icon_qingchu"></image>
					</view>
				</view>
				<view class="w-but">
					<view class="w-but-txt" @click="cancel('tip')">取消</view>
					<view class="w-but-txt" @click="confirm">确认</view>
				</view>
			</view>
		</w-popup>
	</view>
</template>

<script>
	import TIM from 'tim-js-sdk';
	import store from '@/store';
	import {
		mapGetters,
		mapActions,
		mapState
	} from 'vuex';
	import {
		getTimUserSigs,
		getTimUserInfos,
		getCrowdUserLists,
		getSystemMsgLists,
		getCompanyUserInfos,
		getMailLists, //通讯录
	} from '@/common/api.js';
	import wPopup from '@/components/w-popup/w-popup2.vue';
	export default {
		components: {
			wPopup
		},
		data() {
			return {
				chat_type: '',
				title: '',
				showtip: false, //是否显示弹窗1
				content1: '顶部弹 popup',
				type1: '', //弹窗显示方式
				tip_type:'',

				obj: {
					list: [],
				},
				params:{
					company_id:0
				},
				id:0,
				searchVal:'',
				role:false,
				checked1:false,
				checked2:false,
				messageList:[],
				nextReqMessageID:'',
				isCompleted:false
			}
		},
		computed: {
			...mapGetters(['userInfo', 'userSig','companyInfo','contactList']),
		},
		onShow() {
			this.getdata();
			this.getdata2();
		},
		onLoad(option) {
			console.log(222, option)
			this.params.company_id = this.companyInfo.id;
			if (option.title) {
				// 导航栏多语言
				uni.setNavigationBarTitle({
					title: option.title
				});
				this.title = option.title;
			}
			if (option.chat_type) {
				this.chat_type = option.chat_type;
				if(option.chat_type === 'C2C'){
					if(option.id){
						this.id = option.id;
					}
					// 导航栏多语言
					uni.setNavigationBarTitle({
						title: '聊天详情'
					});
				}else if(option.chat_type === 'GROUP'){
					if(option.id){
						this.id = option.id;
					}
					// 导航栏多语言
					uni.setNavigationBarTitle({
						title: '群组详情'
					});
				}
			}
		},
		methods: {
			todet(uid,type){
				let userType = ''
				if(type === 0 || type === 1){
					userType = 'c'
				}else if(type === 2){
					userType = 'd'
				}
				uni.navigateTo({
					url: `/pages/contact/contactDetailInfo?id=${uid}&userType=${userType}`
				})
			},
			getdata2(){
				let _self = this;
				if(this.chat_type === 'GROUP'){
					let promise = this.tim.getGroupProfile({ groupID: this.id});
					promise.then(function(imResponse) {
					  //console.log('获取群资料',imResponse.data.group);
					  const resdata =imResponse.data.group
					  if(resdata.selfInfo.messageRemindType === 'AcceptNotNotify'){
						  console.log('获取群资料',imResponse.data.group);
						  _self.checked1 = true;
					  }
					}).catch(function(imError) {
					  console.log('getGroupProfile error:', imError); // 获取群详细资料失败的相关信息
					});
					let promise2 = this.tim.getConversationProfile('GROUP'+this.id);
					promise2.then(function(imResponse2) {
					  // 获取成功
					  console.log('聊天信息',imResponse2.data.conversation); // 会话资料
					  _self.checked2 = imResponse2.data.conversation.isPinned
					}).catch(function(imError) {
					  console.log('getConversationProfile error:', imError); // 获取会话资料失败的相关信息
					});
				}else if(this.chat_type === 'C2C'){
					let promise = this.tim.getConversationProfile('C2C'+this.id);
					promise.then(function(imResponse) {
					  // 获取成功
					  console.log('聊天信息',imResponse.data.conversation); // 会话资料
					  _self.checked2 = imResponse.data.conversation.isPinned
					}).catch(function(imError) {
					  console.log('getConversationProfile error:', imError); // 获取会话资料失败的相关信息
					});
				}
			},
			getdata(){
				let _self = this;
				_self.obj.list = [];
				if(this.chat_type === 'GROUP'){
					if(this.contactList && this.contactList.length>0){
						const resData = this.contactList.map((item)=>({
							uid:item.uid,
							img:item.img,
							nickname:item.nickname,
							type:item.type
						}));
						console.log(999,resData)
						//获取群列表
						let promise2 = _self.tim.getGroupMemberList({ groupID: this.id, count: 200, offset:0 }); // 从0开始拉取30个群成员
						promise2.then(function(imResponse2) {
						  console.log('成员列表：',imResponse2.data.memberList); // 群成员列表
						  if(resData && resData.length>0){
							  resData.forEach(ite=>{
								  if(imResponse2.data.memberList && imResponse2.data.memberList.length>0){
									  imResponse2.data.memberList.forEach(i=>{
										  if(i.userID === (_self.companyInfo.id + ':' + ite.uid)){
											  _self.obj.list.push(ite)
											  console.log(333,_self.obj.list)
										  }
										  if(i.userID === (_self.companyInfo.id + ':' + _self.userInfo.uid) && (i.role === 'Owner')){
											  _self.role = true; //修改群名称权限
											  console.log(444,_self.role)
										  }
									  })
								  }
							  })
							  _self.$forceUpdate();
						  }
						}).catch(function(imError) {
						  console.warn('getGroupMemberList error:', imError);
						});
					}
				}
			},
			toadd(){
				uni.navigateTo({
					url:`/pages/contact/contactAdd?pageType=addMember&groupID=${this.id}`
				})
			},
			toless(){
				/* uni.navigateTo({
					url:`/pages/contact/contactAdd`jianquMember
				}) */
				console.log(this.obj.list)
				let list = JSON.stringify(this.obj.list)
				uni.navigateTo({
					url:`/pages/contact/contactAdd?pageType=jianquMember&groupID=${this.id}&list=${list}`
				})
				
			},
			confirm() {
				let _self = this;
				if(this.tip_type === 'edit'){
					let promise = _self.tim.updateGroupProfile({
					  groupID: _self.id,
					  name: _self.searchVal, // 修改群名称
					});
					promise.then(function(imResponse) {
					  console.log('修改群名称',imResponse.data.group) // 修改成功后的群组详细资料
					  _self.title = imResponse.data.group.name;
					  uni.showToast({
					  	title:'修改成功!',
						icon:'none',
						duration:2000
					  })
					  _self.getdata()
					}).catch(function(imError) {
					  console.warn('updateGroupProfile error:', imError); // 修改群组资料失败的相关信息
					});
				}else if(this.tip_type === 'jiesan'){
					if(this.role){ //群组解散
						console.log(111,this.obj.list)
						let _self = this;
						let lists = [];
						let is_num = false;
						if(this.obj.list && this.obj.list.length>0){
							this.obj.list.forEach(item=>{
								let list = {
									"userID":item.uid+''
								}
								if(parseInt(item.uid) == parseInt(this.userInfo.uid)){
									
								}else{
									lists.push(list.userID)
								}
							})
						}
						if(lists.length === 0){
							is_num = true;
						}
						let promise = _self.tim.deleteGroupMember({groupID: _self.id, userIDList:lists, reason: '群主解散群了！'});
						promise.then(function(imResponse) {
						  console.log(imResponse.data.group); // 删除后的群组信息
						  console.log('删除群全部成员',imResponse.data.userIDList); // 被删除的群成员的 userID 列表
						  //群主退群
						  let promise2 = _self.tim.quitGroup(_self.id);
						  promise2.then(function(imResponse2) {
						    console.log('解散群成功！',imResponse2.data.groupID); // 退出成功的群 ID
							uni.showToast({
								title:'解散群组成功!',
								icon:'none',
								duration:2000
							})
							setTimeout(() => {
								uni.navigateBack({
									delta:2
								})
							}, 1000);
						  }).catch(function(imError){
						    console.log('quitGroup error:', imError); // 退出群组失败的相关信息
						  });
						}).catch(function(imError) {
						  console.log('deleteGroupMember error:', imError); // 错误信息
						  
						  if(is_num){
							  //当群成员只剩群主时-群主退群
							  let promise2 = _self.tim.quitGroup(_self.id);
							  promise2.then(function(imResponse2) {
							    console.log('解散群成功！',imResponse2.data.groupID); // 退出成功的群 ID
							  							uni.showToast({
							  								title:'解散群组成功!',
							  								icon:'none',
							  								duration:2000
							  							})
							  							setTimeout(() => {
							  								uni.navigateBack({
							  									delta:2
							  								})
							  							}, 1000);
							  }).catch(function(imError){
							    console.log('quitGroup error:', imError); // 退出群组失败的相关信息
							  });
						  }
						  
						});
					}else{ //群退群
						let promise = this.tim.quitGroup(this.id);
						promise.then(function(imResponse) {
						  console.log('退出群组',imResponse.data.groupID); // 退出成功的群 ID
						  uni.showToast({
						  	title:'退出群组成功!',
						  	icon:'none',
						  	duration:2000
						  })
						  setTimeout(() => {
						  	uni.navigateBack({
						  		delta:2
						  	})
						  }, 1000);
						}).catch(function(imError){
						  console.log('quitGroup error:', imError); // 退出群组失败的相关信息
						});
					}
				}else if(this.tip_type === 'qingchu'){
					uni.showLoading({
						mask: true
					})
					_self.messageList = [];
					_self.nextReqMessageID = '';
					_self.isCompleted = false;
					let is_add = false;
					// 打开某个会话时，第一次拉取消息列表
					let promise = this.tim.getMessageList({conversationID: _self.chat_type + _self.id, count: 15});
					promise.then(function(imResponse) {
					  console.log('聊天记录：',imResponse)
					  _self.messageList = imResponse.data.messageList; // 消息列表。
					  //_self.nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
					  _self.isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
					  
					  // 删除消息，v2.12.0起支持
					  let promise2 = _self.tim.deleteMessage(imResponse.data.messageList);
					  promise2.then(function(imResponse2) {
					    // 删除消息成功
					    console.log('删除成功！')
					  }).catch(function(imError2) {
					    // 删除消息失败
					    console.log('deleteMessage error:', imError2);
					  });
					  _self.ifHolidayfun(imResponse.data.nextReqMessageID,100) 
					  console.log(111111,_self.messageList,_self.isCompleted)
					  
					  uni.hideLoading()
					  uni.showToast({
					  	title:'清空成功！',
						icon:'none',
						duration: 2000
					  })
					  _self.$util.prePage(2).getData2();
					  setTimeout(() => {
					  	uni.navigateBack({
					  		delta: 2,
					  	})
					  }, 500)
					  
					}).catch(function(imError){
						  console.log('quitGroup error:', imError); // 退出群组失败的相关信息
						  uni.hideLoading()
					});
				}
				this.showtip = false;
			},
			getifHoliday(nextReqMessageID) {
				let _self = this;
			      return new Promise(resolve => {
			      //此接口为循环调用的接口，按照自己的需要进行修改
					let promise2 = _self.tim.getMessageList({conversationID: _self.chat_type +_self.id,nextReqMessageID, count: 15});
					promise2.then(function(imResponse2) {
						console.log('聊天记录',nextReqMessageID,imResponse2)
					  resolve(imResponse2);
					});
			      });
			},
			async ifHolidayfun(nextReqMessageID , num) {
				let _self = this;
				_self.nextReqMessageID = nextReqMessageID
				console.log(2,_self.nextReqMessageID)
			    //num为需要循环的次数，可以动态传参，可以写死
			    for (let i = 0; i < num; i++) {
			        let ifHoliday = await _self.getifHoliday(_self.nextReqMessageID);
			        //ifHoliday 为接口的响应
			        if (!ifHoliday.data.isCompleted && ifHoliday.data.messageList.length>0) { //此处的1为接口返回是否有目标数据的标识，可根据实际接口返回修改
						_self.messageList.push(...ifHoliday.data.messageList);
					    _self.nextReqMessageID = ifHoliday.data.nextReqMessageID;
						
						// 删除消息，v2.12.0起支持
						let promise = _self.tim.deleteMessage(ifHoliday.data.messageList);
						promise.then(function(imResponse) {
						  // 删除消息成功
						  console.log('删除成功！')
						}).catch(function(imError) {
						  // 删除消息失败
						  console.log('deleteMessage error:', imError);
						});
			        } else if(ifHoliday.data.isCompleted && ifHoliday.data.messageList.length>0){
						console.log(1112)
						_self.messageList.push(...ifHoliday.data.messageList);
						
						// 删除消息，v2.12.0起支持
						let promise = _self.tim.deleteMessage(ifHoliday.data.messageList);
						promise.then(function(imResponse) {
						  // 删除消息成功
						  console.log('删除成功！')
						}).catch(function(imError) {
						  // 删除消息失败
						  console.log('deleteMessage error:', imError);
						});
			         //如果获取到目标数据，在ifHoliday中拿到目标数据并且跳出循环！结束
			          break;
			        }else if(ifHoliday.data.isCompleted && ifHoliday.data.messageList.length === 0){
						console.log(1113)
						break;
					}  
			    }
			},
			
			//跳转聊天界面
			tomsg(id) {
				uni.navigateTo({
					url: ``
				})
			},
			//消息免打扰
			switchChange1(e) {
				console.log(2, e)
				let _self = this;
				if(e.detail.value){
					// 消息免打扰
					let promise = this.tim.setMessageRemindType({ groupID: _self.id, messageRemindType: TIM.TYPES.MSG_REMIND_ACPT_NOT_NOTE });
					promise.then(function(imResponse) {
					  console.log('设置消息免打扰！',imResponse.data.group.selfInfo); // 当前用户在群组中的信息
					}).catch(function(imError) {
					  console.log('setMessageRemindType error:', imError);
					});
				}else{
					// 消息免打扰
					let promise = this.tim.setMessageRemindType({ groupID: _self.id, messageRemindType: TIM.TYPES.MSG_REMIND_ACPT_AND_NOTE });
					promise.then(function(imResponse) {
					  console.log('关闭消息免打扰！',imResponse.data.group.selfInfo); // 当前用户在群组中的信息
					}).catch(function(imError) {
					  console.log('setMessageRemindType error:', imError);
					});
				}
			},
			switchChange2(e) {
				console.log(2, e)
				let _self = this;
				if(e.detail.value){
					// 置顶会话，v2.14.0起支持
					let promise = this.tim.pinConversation({ conversationID:_self.chat_type + _self.id, isPinned: true });
					promise.then(function(imResponse) {
					  // 置顶会话成功
					  const { conversationID } = imResponse.data; // 被置顶的会话 ID
					  console.log('置顶成功！',imResponse)
					}).catch(function(imError) {
					  console.log('pinConversation error:', imError); // 置顶会话失败的相关信息
					});
				}else{
					// 取消置顶会话，v2.14.0起支持
					let promise = this.tim.pinConversation({ conversationID:_self.chat_type + _self.id, isPinned: false });
					promise.then(function(imResponse) {
					  // 取消置顶会话成功
					  const { conversationID } = imResponse.data; // 被取消置顶的会话 ID
					   console.log('取消置顶！',imResponse)
					}).catch(function(imError) {
					  console.log('pinConversation error:', imError); // 取消置顶会话失败的相关信息
					});
					
				}
			},
			jiesan(type){
				if(type === 'edit'){
					if(this.role){
						this.tip_type = type;
						this.content1 = 'center'
						this.type1 = 'center';
						this.showtip = true;
						this.searchVal = this.title;
					}
				}else{
					this.tip_type = type;
					this.content1 = 'center'
					this.type1 = 'center';
					this.showtip = true;
				}
			},
			//清空
			clear() {
				this.searchVal = '';
			},
			change1(e) {
				if (!e.show) {
					this.showtip = false;
				}
			},
			//取消
			cancel(type) {
				this['show' + type] = false
			},
		}
	}
</script>

<style lang="scss">
	/* 提示窗口 */
	.w-tip {
		/* #ifndef APP-NVUE */
		display: flex;
		flex-direction: column;
		/* #endif */
		width: 80vw;
		border-radius: 10rpx;
		background-color: #fff;
		box-shadow: 0rpx 7rpx 7rpx 0rpx rgba(0, 0, 0, 0.1);
		margin: 30rpx auto 0;
	
		.w-tit {
			font-size: 36rpx;
			font-weight: bold;
			color: $font-color-3;
			line-height: 60rpx;
			height: 60rpx;
			margin-top: 20rpx;
			text-align: center;
		}
	
		.w-but {
			display: flex;
			font-size: 32rpx;
			font-weight: 400;
			color: $font-color-b3;
			height: 84rpx;
			line-height: 84rpx;
	
			.w-but-txt {
				flex: 1;
				text-align: center;
				border-right: 1rpx solid #f5f5f5;
			}
	
			.w-but-txt:last-of-type {
				border-right: none;
			}
		}
	
		.w-con {
			display: flex;
			justify-content: center;
			text-align: center;
			font-size: 32rpx;
			font-weight: 400;
			line-height: 100rpx;
			color: $font-color-9;
			border-bottom: 1rpx solid #f5f5f5;
			.input-row {
				display: flex;
				align-items: center;
				justify-content: space-between;
				width: 100%;
				height: 66rpx;
				background: #fff;
				border-radius: 10rpx;
				background: $uni-bg-color-grey;
				margin: 60rpx 30rpx;
			
				.icon-tb3 {
					width: 34rpx;
					height: 34rpx;
					margin: 0 20rpx;
				}
			
				.input-row-w {
					padding-left: 30rpx;
					text-align: left;
					font-size: 28rpx;
					font-weight: 400;
					line-height: 20px;
					color: $font-color-9;
					width: calc(100% - 74rpx);
				}
			}
		}
	}
	
	.page-content {
		display: flex;
		flex-direction: column;
		background: $uni-bg-color-grey;
		height: 100vh;

		.page-top {
			display: flex;
			flex-wrap: wrap;
			align-items: center;
			margin-top: 30rpx;
			padding: 30rpx 30rpx 0 30rpx;
			background: $uni-bg-color;

			.top-imgs {
				display: flex;
				width: 106rpx;
				height: 106rpx;
				margin: 0 40rpx 30rpx 0;

				.top-img {
					width: 106rpx;
					height: 106rpx;
					border-radius: 10rpx;
				}
			}

			.top-imgs:nth-of-type(5n) {
				margin: 0 0rpx 30rpx 0;
			}

		}

		.page-body {
			margin-top: 30rpx;
			display: flex;
			flex-direction: column;

			.body-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 30rpx;
				background: $uni-bg-color;
				padding: 30rpx;

				.body-box-l {
					font-size: 32rpx;
					color: $font-color-3;
				}

				.body-box-r {
					display: flex;
					align-items: center;
					font-size: 28rpx;
					color: $font-color-9;

					.icon-gd {
						margin-left: 20rpx;
					}
				}
			}
		}

		.body-box2 {
			display: flex;
			flex-direction: column;
			margin-bottom: 30rpx;
			background: $uni-bg-color;
			padding: 0 30rpx;

			.box-cen {
				height: 100rpx;
				line-height: 100rpx;
				display: flex;
				justify-content: space-between;
				border-bottom: 1rpx solid #f5f5f5;

				.box-cen-l {
					font-size: 32rpx;
					color: $font-color-3;
				}
			}

			.box-cen:last-of-type {
				border-bottom: none;
			}
		}

		.body-box3 {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 30rpx;
			background: $uni-bg-color;
			padding: 30rpx;

			.body-box-c {
				font-size: 32rpx;
				color: #FE5252;
			}
		}
	}
</style>
